import org.codehaus.groovy.grails.plugins.flex.FlexUtils;

import flex.messaging.MessageBroker;

class NsGflexGrailsPlugin {
	// the plugin version
	def version = "noDS"	//hasDS noDS
	// the version or versions of Grails the plugin is designed for
	def grailsVersion = "1.3.5 > *"
	//def dependsOn = [services: grailsVersion]
	def observe = ["services"]
	def author = "neoscript"
	def authorEmail = "neoscript@gmail.com"
	// resources that are excluded from plugin packaging
	def pluginExcludes = [
		'scripts/_Events.groovy',
		'lib/ojdbc5.jar',
		'web-app/swf/**',
		(version == "hasDS")?'grails-app/nothing-exclude':'grails-app/**',
		'src/java/flex/messaging/services/remoting/adapters/**'
	]

	def title = "NS Grails Flex"
	def description = 'Integrate your project with BlazeDS and FlexBuilder nature, install simple user/role/menu app with installSimpleApp.'

	// URL to the plugin's documentation
	def documentation = "http://grails.org/plugin/ns-gflex"

	def doWithWebDescriptor = { xml ->

		def useContextClassLoader = (application.config.flatten().containsKey("flex.use.context.classloader") ? application.config.flex.use.context.classloader : true)

		// listeners
		def listeners = xml.listener
		listeners[listeners.size() - 1] + {
			listener {
				'listener-class'("flex.messaging.HttpFlexSession")
			}
		}

		// servlets
		def servlets = xml.servlet
		servlets[servlets.size() - 1] + {
			servlet {
				'servlet-name'("MessageBrokerServlet")
				'servlet-class'("flex.messaging.MessageBrokerServlet")
				'init-param' {
					'param-name'("services.configuration.file")
					'param-value'("/WEB-INF/flex/services-config.xml")
				}
				'init-param' {
					'param-name'("useContextClassLoader")
					'param-value'(useContextClassLoader)
				}
				'load-on-startup'("1")
			}
		}

		// servlet mappings
		def servletMappings = xml.'servlet-mapping'
		servletMappings[servletMappings.size() - 1] + {
			'servlet-mapping' {
				'servlet-name'("MessageBrokerServlet")
				'url-pattern'("/messagebroker/*")
			}
		}
	}

	def onChange = { event ->
		if (event.source) {
			def serviceClass = application.getServiceClass(event.source?.name)
			if (FlexUtils.hasFlexRemotingConvention(serviceClass)) {
				def messageBroker = MessageBroker.getMessageBroker(null)
				def remotingService = FlexUtils.getGrailsRemotingService(messageBroker)
				if (!remotingService.getDestination(serviceClass.propertyName)) {
					FlexUtils.createRemotingDestination(messageBroker, serviceClass)
				}
			}
		}
	}
}
